import axios from 'axios';
import qs from 'qs';
import Vue from 'vue';
import store from '@/store/index';
import { APP } from '@/store/mutationsTypes';

const ax = axios.create();
ax.defaults = Object.assign(ax.defaults, {
  baseURL: process.env.VUE_APP_BASE_URL,
  method: 'post',
  timeout: 60 * 1000,
});
Vue.prototype.loadingAy = [];

function closeLoading() {
  // 关闭遮罩
  // 关闭遮罩
  if (Vue.prototype.loadingAy.length === 1) {
    store.commit(APP.UPDATE_LOADING, false);
  }
  if (Vue.prototype.forceCloseLoding) {
    store.commit(APP.UPDATE_LOADING, false);
    Vue.prototype.loadingAy.length = 0;
    Vue.prototype.forceCloseLoding = false;
  } else {
    Vue.prototype.loadingAy.length && Vue.prototype.loadingAy.length--;
  }
}

function showLoading() {
  /* 打开遮罩 */
  store.commit(APP.UPDATE_LOADING, true);
  return new Date().getTime();
}

let isShowError = false;

function showError(msg, status) {
  /**
   * 提示错误
   * @msg 错误消息
   * @status 状态码
   * */
  if (isShowError) {
    return;
  }
  isShowError = true;
  const msgMap = new Map([
    [/^401$/, '您没有访问权限'],
    [/^403$/, '您没有访问权限'],
    [/^404$/, '您请求的服务不存在'],
    [/^4\d{2}$/, '您请求的方式不正确'],
    [/^501$/, '服务器不支持此类请求'],
    [/^502$/, '服务器网关出错，请稍后重试'],
    [/^503$/, '服务器正在重启，请稍后重试'],
    [/^503$/, '服务器网关超时，请稍后重试'],
    [/^503$/, '服务器不支持此请求协议'],
    [/^5\d{2}$/, '服务器出错，请稍后重试'],
  ]);
  let errorMsg = msg || '请求失败';
  for (const [key, value] of msgMap) {
    if (key.test(status)) {
      errorMsg = value;
      break;
    }
  }
  Vue.prototype.$toast.error(errorMsg);
}

ax.interceptors.request.use(
  (config) => {
    const { headers, noLoading, noToken } = config;
    if (headers && !noToken) {
      headers.Authorization = `Bearer  ${localStorage.getItem('token')}`;
    }
    if (!noLoading) {
      Vue.prototype.loadingAy.push(showLoading());
    }
    return config;
  },
  (error) => {
    if (!error.config.noLoading) {
      closeLoading();
    }
    showError(error);
    return {
      code: -1,
    };
  },
);

ax.interceptors.response.use(
  (res) => {
    const { config, data } = res;
    // 关闭遮罩
    if (!config.noLoading) {
      closeLoading();
    }
    const { code, msg } = data;
    if (!config.noToast) {
      if (code !== '1') {
        showError(msg);
      }
    }
    if (config.returnResponse) {
      return res;
    }
    return data;
  },
  (res) => {
    const { config, response } = res;
    if (!config.noLoading) {
      closeLoading();
    }
    if (!config.noToast) {
      // 状态码
      let status;
      if (response && response.status) {
        status = response.status;
      }
      showError(response.data, status);
    }
    return {
      code: -1,
    };
  },
);

const axGet = function (url, params, options) {
  return ax({
    headers: {
      'content-type': 'application/x-www-form-urlencoded,charset=UTF-8',
    },
    method: 'get',
    url,
    params,
    ...options,
  });
};

const axPost = function (url, data, params, options) {
  return ax({
    method: 'post',
    url,
    data: qs.stringify(data),
    params,
    ...options,
  });
};

const axPostJson = function (url, data, params, options) {
  return ax({
    method: 'post',
    url,
    data,
    params,
    ...options,
  });
};
export default ax;

export { axGet, axPost, axPostJson };
